﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
using CMN.Extends;
using System.Text;

namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Extend_CollectSetInfoController : Controller
    {

        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View("Index");//页面地址
        }

        /// <summary>
        /// 批量启用采集规则设置
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string UpdateEnabled(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {
                string[] list = Utils.SplitString(actionId, "_");
                string strUpdate = Utils.ArrayToString(list, ",", false);
             IUpdateDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
             if (Extend_CollectSetInfoSv.UpdateList(" id in ("+strUpdate+")","Enabled=1") == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 批量启用自动更新采集规则设置
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string UpdateIsAutoUpdate(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {
                string[] list = Utils.SplitString(actionId, "_");
                string strUpdate = Utils.ArrayToString(list, ",", false);
                IUpdateDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
                if (Extend_CollectSetInfoSv.UpdateList(" id in (" + strUpdate + ")", "IsAutoUpdate=1") == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 返回采集规则设置列表
        /// </summary>
        /// <returns>json</returns>
        public string List()
        {
            //返回json数组

            int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
            int pageIndex = (int)Utils.GetQueryAndFormString("start", this, 9, 1, DataType.Int);
            string sort = (string)Utils.GetQueryAndFormString("sort", this, 100, 0, DataType.Str);
            QueryParam qp = new QueryParam();
            if (!string.IsNullOrEmpty(sort))
            {
                SortEntity sortEntity = null;
                List<SortEntity> sortList = new List<SortEntity>();
                sortList = (List<SortEntity>)JsonConvert.DeserializeObject(sort, typeof(List<SortEntity>));
                if (sortList.Count > 0)
                {
                    sortEntity = sortList[0];
                }

                qp.PageIndex = pageIndex / pageSize + 1;
                qp.PageSize = pageSize;
                if (sortEntity != null)
                    qp.Orderfld = string.Concat(sortEntity.Property, " ", sortEntity.Direction);
            }
            int recordNum = 0;
            IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
            IDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
            List<Extend_CollectSetInfoEntity> extend_collectsetinfoList = Extend_CollectSetInfoSv.List(qp, out recordNum);
            returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(extend_collectsetinfoList, Formatting.Indented, jsDataConvert), "}");
            return returnJson;

        }

        /// <summary>
        /// 查看采集规则设置 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
            IDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
            int intId = Utils.StringToInt(actionId, 0);
            Extend_CollectSetInfoEntity extend_collectsetinfo = Extend_CollectSetInfoSv.Look(intId);
            IDataService<Normal_ChannelEntity> Normal_ChannelSv = ServiceBuilder.BuildNormal_ChannelService();
            Normal_ChannelEntity channel = Normal_ChannelSv.Look(extend_collectsetinfo.ChannelId);
            extend_collectsetinfo.ChannelName = channel.Title;
            if (extend_collectsetinfo != null)
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(extend_collectsetinfo), "}");
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }



        /// <summary>
        /// 查看采集规则设置 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string UpdateIsPass(string actionId)
        {
            IUpdateDataService<Extend_CollectContentEntity> sv = ServiceBuilder.BuildExtend_CollectContentService();
            if (sv.UpdateList(string.Concat("CollectSetId=",actionId)," ispass=1 ")=="")
                returnJson = "{success:'true'}";
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 查看采集规则设置 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Copy(string actionId)
        {
            IDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
            int intId = Utils.StringToInt(actionId, 0);
            Extend_CollectSetInfoEntity extend_collectsetinfo = Extend_CollectSetInfoSv.Look(intId);
            extend_collectsetinfo.DataTable_Action = DataTableAction.Insert ;
            extend_collectsetinfo.Name = string.Concat("copy", extend_collectsetinfo.Name);
            extend_collectsetinfo.CollectTime = null;
            if (Extend_CollectSetInfoSv.Insert(extend_collectsetinfo) == "")
                returnJson = "{success:'true'}";
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 更新采集规则设置
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        [ValidateInput(false)]
        public string Update(string actionId)
        {
            int intId = Utils.StringToInt(actionId, 0);
            if (intId != 0)
            {
                Extend_CollectSetInfoEntity extend_collectsetinfo = GetExtend_CollectSetInfo();
                extend_collectsetinfo.Id = intId;
                IDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
                if (Extend_CollectSetInfoSv.Update(extend_collectsetinfo) == "")
                {
                    returnJson = "{success:'true'}";
                    CMN.Extends.Job.CacheCollcetSet.ClearCache();
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }

            return returnJson;
        }
        [ValidateInput(false)]
        public string CollectList()
        {
            Extend_CollectSetInfoEntity extend_collectsetinfo = GetExtend_CollectSetInfo();
           
            string strUrl = (string)Utils.GetQueryAndFormString("UrlList", this, 200, 0, DataType.Str);
            CollectHelper chelper = new CollectHelper();
            
            List<Extend_CollectLinkInfoEntity> collectLinkList2 = new List<Extend_CollectLinkInfoEntity>();
            collectLinkList2 = chelper.GetLinks(extend_collectsetinfo);
            StringBuilder sb = new StringBuilder();

            foreach(Extend_CollectLinkInfoEntity linkInfo  in collectLinkList2){
                sb.Append(linkInfo.Url + System.Environment.NewLine);
                  
                    
            }
            return returnJson = "{success:'true',message:'"+JsonConvert.SerializeObject( sb.ToString())+"'}";
        }
        [ValidateInput(false)]
        public string CollectContent()
        {
            Extend_CollectSetInfoEntity extend_collectsetinfo = GetExtend_CollectSetInfo();
         
            string strUrl = (string)Utils.GetQueryAndFormString("UrlContent", this, 200, 1, DataType.Str);
            CollectHelper chelper = new CollectHelper();
            Extend_CollectContentEntity cContent = new Extend_CollectContentEntity();
            if (extend_collectsetinfo.IsPaging)
            {
                cContent = chelper.GetPagingContent(extend_collectsetinfo, strUrl);
            }
            else
                cContent = chelper.GetContent(extend_collectsetinfo, strUrl);

            return returnJson = "{success:'true',message:'" + JsonConvert.SerializeObject(cContent.Title) + "/r/n" + JsonConvert.SerializeObject(cContent.Tags) + "/r/n" + JsonConvert.SerializeObject(cContent.Summary) + "/r/nImg:" + JsonConvert.SerializeObject(cContent.Img) + "/r/n" + "/r/nAddate:" + JsonConvert.SerializeObject(cContent.AddDate.ToString()) + "/r/n"+ "/r/n:Author" + JsonConvert.SerializeObject(cContent.Author) + "/r/n" +JsonConvert.SerializeObject(cContent.TextContent.Replace("\t", "").Replace("'", "") + "/r/n" + "editor" + "/r/n" + cContent.Editor + "/r/n" + "Remark" + "/r/n" + JsonConvert.SerializeObject(cContent.Remark.Replace("'", "")), Formatting.Indented) + "'}"; ;
        }
        [ValidateInput(false)]
        protected Extend_CollectSetInfoEntity GetExtend_CollectSetInfo()
        {
            
           Extend_CollectSetInfoEntity extend_collectsetinfo = new Extend_CollectSetInfoEntity();
            extend_collectsetinfo.DataTable_Action = DataTableAction.Insert;
            extend_collectsetinfo.Name = (String)Utils.GetQueryAndFormString("Name", this, 100, 1, DataType.Str);
            extend_collectsetinfo.Url = (String)Utils.GetQueryAndFormString("Url", this, 550, 1, DataType.Str);
            extend_collectsetinfo.Encoding = (String)Utils.GetQueryAndFormString("Encoding", this, 20, 1, DataType.Str);
            extend_collectsetinfo.IncludeStr = (String)Utils.GetQueryAndFormString("IncludeStr", this, 200, 1, DataType.Str);
            extend_collectsetinfo.StartNum = (Int32)Utils.GetQueryAndFormString("StartNum", this, 10, 1, DataType.Int);
            extend_collectsetinfo.EndNum = (Int32)Utils.GetQueryAndFormString("EndNum", this, 10, 1, DataType.Int);
            extend_collectsetinfo.AddNum = (Int32)Utils.GetQueryAndFormString("AddNum", this, 10, 1, DataType.Int);
            extend_collectsetinfo.WithoutStr = (String)Utils.GetQueryAndFormString("WithoutStr", this, 200, 0, DataType.Str);
            extend_collectsetinfo.Enabled = (bool)Utils.GetQueryAndFormString("Enabled", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsAutoUpdate = (bool)Utils.GetQueryAndFormString("IsAutoUpdate", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.ChannelId = (Int32)Utils.GetQueryAndFormString("ChannelId", this, 10, 0, DataType.Int);
            extend_collectsetinfo.TitleReplaceStr = (String)Utils.GetQueryAndFormString("TitleReplaceStr", this, 500, 0, DataType.Str);
            extend_collectsetinfo.IsAutoKeyWord = (bool)Utils.GetQueryAndFormString("IsAutoKeyWord", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsAutoDescription = (bool)Utils.GetQueryAndFormString("IsAutoDescription", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsIncludeHtml = (bool)Utils.GetQueryAndFormString("IsIncludeHtml", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.ContentMatchLeft = (String)Utils.GetQueryAndFormString("ContentMatchLeft", this, 1000, 1, DataType.Str);
            extend_collectsetinfo.ContentMatchRight = (String)Utils.GetQueryAndFormString("ContentMatchRight", this, 1000, 1, DataType.Str);
            extend_collectsetinfo.ContentRemoveLeftLength = (Int32)Utils.GetQueryAndFormString("ContentRemoveLeftLength", this, 10, 0, DataType.Int);
            extend_collectsetinfo.ContentRemoveRightLength = (Int32)Utils.GetQueryAndFormString("ContentRemoveRightLength", this, 10, 0, DataType.Int);
            extend_collectsetinfo.ContentReplaseStr = (String)Utils.GetQueryAndFormString("ContentReplaseStr", this, 1000, 0, DataType.Str);
            extend_collectsetinfo.IsIncludeScript = (bool)Utils.GetQueryAndFormString("IsIncludeScript", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsIncludeClass = (bool)Utils.GetQueryAndFormString("IsIncludeClass", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsIncludeStyle = (bool)Utils.GetQueryAndFormString("IsIncludeStyle", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsIncludeColor = (bool)Utils.GetQueryAndFormString("IsIncludeColor", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsIncludeLink = (bool)Utils.GetQueryAndFormString("IsIncludeLink", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsIncludeImg = (bool)Utils.GetQueryAndFormString("IsIncludeImg", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsIncludeFile = (bool)Utils.GetQueryAndFormString("IsIncludeFile", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsIncludeFrame = (bool)Utils.GetQueryAndFormString("IsIncludeFrame", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsPaging = (bool)Utils.GetQueryAndFormString("IsPaging", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.PagingReg = (String)Utils.GetQueryAndFormString("PagingReg", this, 100, 0, DataType.Str);
            extend_collectsetinfo.CollectTime = (DateTime?)Utils.GetQueryAndFormString("CollectTime", this, 23, 0, DataType.Dat);
            extend_collectsetinfo.Cookie = (String)Utils.GetQueryAndFormString("Cookie", this, 2147483647, 0, DataType.Str);
            extend_collectsetinfo.ThreadInterval = (Int32)Utils.GetQueryAndFormString("ThreadInterval", this, 10, 0, DataType.Int);
            extend_collectsetinfo.OrderNum = (Int32)Utils.GetQueryAndFormString("OrderNum", this, 10, 0, DataType.Int);
            extend_collectsetinfo.DoTime = (Int32)Utils.GetQueryAndFormString("DoTime", this, 10, 1, DataType.Int);
            extend_collectsetinfo.ListMatchLeft = (String)Utils.GetQueryAndFormString("ListMatchLeft", this, 1000, 0, DataType.Str);
            extend_collectsetinfo.ListMatchRight = (String)Utils.GetQueryAndFormString("ListMatchRight", this, 1000, 0, DataType.Str);
            extend_collectsetinfo.TitleMatchLeft = (String)Utils.GetQueryAndFormString("TitleMatchLeft", this, 1000, 0, DataType.Str);
            extend_collectsetinfo.TitleMatchRight = (String)Utils.GetQueryAndFormString("TitleMatchRight", this, 1000, 0, DataType.Str);
            extend_collectsetinfo.FirstUrl = (String)Utils.GetQueryAndFormString("FirstUrl", this, 1000, 0, DataType.Str);
            extend_collectsetinfo.IsAutoImg = (bool)Utils.GetQueryAndFormString("IsAutoImg", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.IsRecommend = (bool)Utils.GetQueryAndFormString("IsRecommend", this, 6, 0, DataType.Bool);
            extend_collectsetinfo.UrlRegex = (String)Utils.GetQueryAndFormString("UrlRegex", this, 100, 0, DataType.Str);
            extend_collectsetinfo.ContentEncoding = (String)Utils.GetQueryAndFormString("ContentEncoding", this, 20, 0, DataType.Str);
            extend_collectsetinfo.FormatStr = (String)Utils.GetQueryAndFormString("FormatStr", this, 2000, 0, DataType.Str);
            extend_collectsetinfo.SecondUrlRegex = (String)Utils.GetQueryAndFormString("SecondUrlRegex", this, 200, 0, DataType.Str);
            extend_collectsetinfo.SecondContentRegex = (String)Utils.GetQueryAndFormString("SecondContentRegex", this, 800, 0, DataType.Str);
                
            return extend_collectsetinfo;
        }

        /// <summary>
        /// 新增采集规则设置
        /// </summary>
        /// <returns>json</returns>
        [ValidateInput(false)]
        public string Insert()
        {
            Extend_CollectSetInfoEntity extend_collectsetinfo = GetExtend_CollectSetInfo();
           
            IDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
            if (Extend_CollectSetInfoSv.Insert(extend_collectsetinfo) == "")
            {
                returnJson = "{success:'true'}";
                CMN.Extends.Job.CacheCollcetSet.ClearCache();
            }
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 删除采集规则设置
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            int intId = Utils.StringToInt(actionId, 0);
            if (intId != 0)
            {
                Extend_CollectSetInfoEntity extend_collectsetinfo = new Extend_CollectSetInfoEntity();
                extend_collectsetinfo.Id = intId;
                IDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
                if (Extend_CollectSetInfoSv.Delete(extend_collectsetinfo) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 批量删除采集规则设置
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {

                IDataService<Extend_CollectSetInfoEntity> Extend_CollectSetInfoSv = ServiceBuilder.BuildExtend_CollectSetInfoService();
                if (Extend_CollectSetInfoSv.DeleteList(actionId) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

    }
}
